﻿from mod_python import apache

from pygs_client import *
import time

# get pygsSoap client
pygsSoap = pygsLocator().getpygsSoap()  

def handler(req):
    # define handlers
    handlers = {
        "getTrek": getTrek,
        "login": login
        }
   
    # parse URL query 
    query = req.parsed_uri[apache.URI_QUERY]
    parsedQuery =  parseQuery(query)
    # call handler
    handlers[parsedQuery["call"]](req, parsedQuery)    
    return apache.OK

def getTrek(req, parsedQuery):
    req.content_type = 'text/xml'
    # make soap request
    soapRequest = getTrekSoapIn()
    soapRequest._token = parsedQuery["token"]
    soapRequest._trekingObjectId = int(parsedQuery["trekingObjectId"])
    if parsedQuery.has_key("dateFrom"):
        dateFrom = time.strptime(parsedQuery["dateFrom"], "%Y%m%d%X")
    else:
        dateFrom = time.strptime("1900-01-01 00:00:00", "%Y-%m-%d %X")
    if parsedQuery.has_key("dateTo"):
        dateTo = time.strptime(parsedQuery["dateTo"], "%Y%m%d%X")
    else:
        dateTo = time.strptime("2100-12-31 00:00:00", "%Y-%m-%d %X")
    soapRequest._dateFrom = dateFrom
    soapRequest._dateTo = dateTo
    
    # get soap response
    soapResponse = pygsSoap.getTrek(soapRequest)    
    result = soapResponse._getTrekResult 
    
    req.write("%s" % result)

def login(req, parsedQuery):
    req.content_type = 'text/plain'   
    # make soap request
    soapRequest = loginSoapIn()
    if not (parsedQuery.has_key("user") and parsedQuery.has_key("pass")):
        req.write("'user' or 'pass' param not specified!")
        return
    
    soapRequest._userName = parsedQuery["user"]
    soapRequest._password = parsedQuery["pass"]    

    # get soap response
    try:
        soapResponse = pygsSoap.login(soapRequest)    
        result = soapResponse._loginResult 
        req.write("%s" % result)
    except:
        req.write("Something Wrong!")


def parseQuery(query):
    paramPairs = query.split("&")
    params = {}
    for pair in paramPairs:
        keyValue = pair.split("=")
        params[keyValue[0]] = keyValue[1]
    return params